import store from '@/store' 
import { getToken } from '@/utils/auth'
let connecting = false;
let timeoutObj = undefined;
let serverTimeoutObj = undefined;
export default {
  ws: {},
  //初始化ws
  initWs(){
    let _this = this;
    let token = getToken()
    if ('WebSocket' in window && token) {
      // 创建websocket
      connecting = true;
      const ws = new WebSocket(process.env.VUE_APP_WS_API+token)
      _this.ws = ws;
      ws.onopen = function(evt){
        // WebSocket 已连接
        connecting = false;
        console.log('连接成功')
        //发送心跳
        _this.longstart()
      }
      ws.onmessage = function(evt){
        //收到内容、重置心跳
        _this.longstart();
        if(evt.data==1){
          //心跳内容、忽略
        }else{
          //console.log('数据接收', evt.data)
          store.commit("SET_WS_DATA",evt.data)
        }
      }
      ws.onclose = function(){
        console.log("连接已关闭");
        if(getToken()&&!connecting){
          //重连
          setTimeout(() => {
            _this.initWs()
          }, 2000)
        }

      }
      // 异常断开重连
      ws.onerror = function(err){
        connecting = false;
        console.log('websocket 断开: ' + err, ws.readyState)
        console.log(ws.readyState)
        // if (ws.readyState != 0) {
        //   setTimeout(() => {
        //     _this.initWs(userId)
        //   }, 1000)
        // }
      }
    }
  },
  //发送ws方法
  sendWs(data) {
    console.log(data, 'send')
    try{
      this.ws.send(data)
    }catch(err){
      console.log('websocket connecty error')
    }
  },
  //断开socked方法
  closeWs(){
    console.log('关闭ws')
    if(this.ws){
      try{
        this.ws.close()
      }catch{
        
      }
    }
  },
  //心跳
  longstart() {
    //通过关闭定时器和倒计时进行重置心跳
    clearInterval(timeoutObj)
    clearTimeout(serverTimeoutObj);
    //每隔30s发送一个1
    timeoutObj = setInterval(()=>{
        // console.log('重置监测心跳')
        this.ws.send('1')
        // 发送数据 2s后没有接收到返回的数据进行关闭websocket重连
        serverTimeoutObj = setTimeout(()=>{
            // console.log("心跳停止");
            this.ws.close();
        }, 2000);
    },30000)
  },
}
